﻿/**
 *	Your MP Gadget for Google Desktop Search
 *	Copyright 2007-2008 Douglas Bromley <doug.bromley+yourmp@gmail.com>
 *	http://www.straw-dogs.co.uk
 *	Released under the GNU Public License
 */

var apiKey = "Dtzx3ADQM2VvDtR34JBBDZDw";
var theyWorkForYouUrlBasic = 'http://www.theyworkforyou.com/api/getMP?key=' + apiKey + '&output=js';
var theyWorkForYouUrlMore = 'http://www.theyworkforyou.com/api/getMPInfo?key=' + apiKey + '&output=js';
var theyWorkForYouUrlDebates = 'http://www.theyworkforyou.com/api/getDebates?key=' + apiKey + '&type=commons&output=js';

/**
 * Executed on gadget open.
 */
function view_onOpen(){
	// Check every 30 mins by default
	var check_time = 60 * 30 * 1000;

	if(options.getValue('checkInterval') != undefined && options.getValue('checkInterval') > 0){
		check_time = 60 * 1000 * parseInt(options.getValue('checkInterval'));
	}

	retrieveMpInfo();
	view.setInterval(retrieveMpInfo, check_time);
}
/**
 * Execute the MpInfo retrieval after the user has changed options
 */	
function onOptionChanged(){
	retrieveMpInfo();
}
/**
 * Get the basic info for MP such as name, party and constituency
 * From there it then executes the functions for profile sites 
 * and debates information
 */
function retrieveMpInfo(){
	if(options.getValue("postcode").length <= 0){
		lblMpInfo.innerText = 'Please enter your post code into the options';
	}else{		
		var postcode = options.getValue('postcode');
		var request = new XMLHttpRequest();
		var requestUrl = theyWorkForYouUrlBasic + '&postcode=' + postcode;
		request.onreadystatechange = onReadyStateChange;

		try{
			request.open('GET', requestUrl, true);
			request.send();
		}catch(e){
			onRequestError();
			return;
		}

		var timeoutTimer = null;
		timeoutTimer = view.setTimeout(onRequestError, getRetryDelay());
	}

  function onReadyStateChange() {
    if (request.readyState != 4) {
      return;
    }

    if (request.status != 200) {
			return;
		}

		if (timeoutTimer) {
			view.clearTimeout(timeoutTimer);
		}

		mpInfoArray = eval("(" + request.responseText + ")");
		debug.trace(request.responseText);

		mpPersonId = mpInfoArray['person_id'];

		mpInfo = mpInfoArray['first_name'] + ' ' + mpInfoArray['last_name'];
		mpInfo += "\nConstituency: " + mpInfoArray['constituency'];
		mpInfo += "\nParty: " + mpInfoArray['party'];

		lblMpInfo.innerText = mpInfo;

		if(options.getValue('showPhoto')){
			loadPhoto(mpInfoArray['image']);
		}else{
			mpPhoto.src = 'Portcullis_Sml.jpg';
		}
		
		getFurtherInfo(mpPersonId);
		getDebateInfo(mpPersonId);
  }

  function onRequestError() {
    request.abort();
    debug.warning('Request error, will retry later.');
    view.setTimeout(retrieveMpInfo, getRetryDelay());
  }

}

function getFurtherInfo(person_id){
	var request = new XMLHttpRequest();
	var requestUrl = theyWorkForYouUrlMore + '&id=' + person_id
	request.onreadystatechange = onReadyStateChange;
	debug.trace('Visiting further info: ' + requestUrl);

  try{
    request.open('GET', requestUrl, true);
    request.send();
  }catch(e){
    onRequestError();
    return;
  }

  var timeoutTimer = null;

	// Want to set a timeout since no data is available.
	// If request timesout, call onRequestError to retry.
	timeoutTimer = view.setTimeout(onRequestError, getRetryDelay());

  function onReadyStateChange() {
    if (request.readyState != 4) {
      return;
    }

    if (request.status != 200) {
			return;
		}
		if (timeoutTimer) {
			debug.warning('Cancelling request timeout timer.');
			view.clearTimeout(timeoutTimer);
		}
		
		// Make sure we've not already put expenses in
		if(lblMpInfo.innerText.search(/Expenses/) < 0){
			mpMoreInfoArray = eval("(" + request.responseText + ")");

			mpInfo = lblMpInfo.innerText;
			expenses = "£" + mpMoreInfoArray['expenses2007_total'];
			mpInfo += "\nExpenses (2007): " + expenses;

			lblMpInfo.innerText = mpInfo;
		}

		linkBbcProfile.href = mpMoreInfoArray['by_member_id'][1]['bbc_profile_url'];
		linkWikiEntry.href = mpMoreInfoArray['wikipedia_url'];
		linkGuardianEntry.href = mpMoreInfoArray['guardian_mp_summary'];
		return;
  }

  function onRequestError() {
    request.abort();
    debug.warning('Request error, will retry later.');
    view.setTimeout(getFurtherInfo, getRetryDelay());
  }
}

function getDebateInfo(person_id){
	var request = new XMLHttpRequest();
	var requestUrl = theyWorkForYouUrlDebates + '&person=' + person_id;
	var debateInfo;
	request.onreadystatechange = onReadyStateChange;

  try {
    request.open('GET', requestUrl, true);
    request.send();
  } catch(e) {
    onRequestError();
    return;
  }

  var timeoutTimer = null;
	timeoutTimer = view.setTimeout(
			onRequestError,
			getRetryDelay()
		);

  function onReadyStateChange() {
    if (request.readyState != 4) {
      return;
    }

    if (request.status != 200) {
			return;
		}
		if (timeoutTimer) {
			view.clearTimeout(timeoutTimer);
		}
		mpDebInfoArray = eval("(" + request.responseText + ")");
		
		for(i=0;i<6;i++){
			var item = new ContentItem();
			item.layout = gddContentItemLayoutNews;
			item.heading = mpDebInfoArray.rows[i].body;
			item.snippet = mpDebInfoArray.rows[i].body;
			item.tooltip = mpDebInfoArray.rows[i].body;

			var d=new Date();
			hdate = mpDebInfoArray.rows[i].hdate.split("-");
			
			d.setDate(hdate[2]);
			d.setMonth((hdate[1]-1));
			d.setYear(hdate[0]);

			item.time_created = d.getVarDate();
			item.open_command = "http://www.theyworkforyou.com" + mpDebInfoArray.rows[i].listurl;
			item.source = "TheyWorkForYou";
			contentarea1.AddContentItem(item, gddItemDisplayInSidebar);
		}
  }

  function onRequestError() {
    request.abort();
    debug.warning('Request error, will retry later.');
    view.setTimeout(getFurtherInfo, getRetryDelay());
  }
}
/**
 * Returns the millisecond retry delay
 */
function getRetryDelay() {
  return 10000;	// Ten seconds
}

/**
 * Loads an image into an img control when given an http url
 * @author Robert (profilemd@gmail.com) on GDS Google Group
 */
function loadPhoto(img) {
  var http = new XMLHttpRequest(); 
  var url = "http://www.theyworkforyou.com" + img; 
	debug.trace('Gonna load: ' + url);
  http.onreadystatechange = onData;
  http.open("GET", url, "true");
  http.send();
  function onData() { 
    if (http.readyState == 4) { 
      if (http.status == 200) { 
        var source = http.responseStream;
				mpPhoto.src = source;
      } 
      else { // status != 200 
        imageControl.src = "placeholder.png"; 
      } 
    } 
  } 
}
